package cn.com.connext.scrm.web.rest;

import cn.com.connext.scrm.service.MemberService;
import cn.com.connext.scrm.service.dto.JsonResult;
import cn.com.connext.scrm.service.dto.MemberDTO;
import cn.com.connext.scrm.service.dto.SmsDTO;
import cn.com.connext.scrm.web.rest.errors.MyErrorCode;
import cn.com.connext.scrm.web.rest.req.CrmMemberReq;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.codahale.metrics.annotation.Timed;
import com.connext.common.exception.ServiceException;
import com.connext.common.web.rest.BaseResource;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.net.URISyntaxException;
import java.util.concurrent.TimeoutException;

/**
 * 会员
 */
@RestController
@RequestMapping("/api/member")
public class MemberResource extends BaseResource {
    private final Logger log = LoggerFactory.getLogger(NoteResource.class);
    @Autowired
    private MemberService memberService;

    public MemberResource() throws TimeoutException {
        super("Member");
    }

    /**
     * 查看会员信息
     */
    @GetMapping("/getMemberInfo")
    @ApiOperation(value = "查看一个会员", tags = {"会员信息"}, notes = "查看一个会员")
    public ResponseEntity<JSONObject> getMenberInfo(MemberDTO memberDTO) {
        log.info("查看会员信息开始: {}", memberDTO.getMembershipId());
        if (StringUtils.isEmpty(memberDTO.getMembershipId())) {
            throw new ServiceException(MyErrorCode.ERROR_MESSAGE_ISNULL);
        }
        //请求外部系统
        ResponseEntity<JSONObject> membDTO = memberService.findOneDTO(memberDTO.getMembershipId());
        log.info("查看会员信息结束: {}", membDTO);
        return entityResponse(membDTO.getBody());
    }

    /**
     * 修改会员信息
     */
    @PutMapping("/updateMemberInfo")
    @ApiOperation(value = "修改会员信息", tags = {"会员信息"}, notes = "修改会员信息")
    public JsonResult updateMemberInfo(@RequestBody CrmMemberReq req) {
        log.info("修改会员信息开始 : {}", JSON.toJSONString(req));
        if (null == req) {
            throw new ServiceException(MyErrorCode.ERROR_MESSAGE_ISNULL);
        }
        JsonResult result = memberService.update(req);
        return result;
    }

    /**
     * 修改会员手机号
     */
    @PutMapping("/updateMobile")
    public JsonResult updateMobile(@RequestBody JSONObject jsonObject) {
        log.info("修改会员手机号开始 : {}", jsonObject.getString("userId"));
        if (jsonObject.getString("newMobile").isEmpty() || jsonObject.getString("userId").isEmpty() || jsonObject.getString("oldMobile").isEmpty()) {
            throw new ServiceException(MyErrorCode.ERROR_MESSAGE_ISNULL);
        } else if (false == memberService.isMobileNO(jsonObject.getString("newMobile"))) {
            throw new ServiceException(MyErrorCode.ERROR_MOBILE_FORMAT);
        } else {
            JsonResult result = memberService.updateMobile(jsonObject);
            log.info("修改会员手机号结束 : {}", result);
            return result;
        }
    }

    /**
     * 会员注册
     */
    @PostMapping("/onlineMembership")
    @ApiOperation(value = "会员注册", tags = {"会员信息"}, notes = "会员注册")
    public ResponseEntity<MemberDTO> onlineMembership(@RequestBody MemberDTO memberDTO) throws URISyntaxException {
        log.info(" 会员注册信息开始: {}", memberDTO.getUnionId());
        log.info(" 会员注册信息参数: {}", memberDTO.toString());
        if (null == memberDTO) {
            throw new ServiceException(MyErrorCode.ERROR_MESSAGE_ISNULL);
        }
        //添加信息
        JSONObject object = memberService.saveMemberInfo(memberDTO);
        log.info(" 会员注册信息结束: {}", object);
        return createSuccess(object);
    }

    /**
     * 短信验证码
     *
     * @param phone
     * @return
     */
    @PostMapping("/sendSms/{phone}")
    @Timed
    @ApiOperation(value = "发送短信验证码至phone", tags = "短信发送", notes = "发送短信验证码至phone")
    public ResponseEntity<SmsDTO> sendSms(@PathVariable String phone) {
        SmsDTO smsDTO = memberService.sendCodeSms(phone);
        return entityResponse(smsDTO);
    }

    /**
     * 验证短信验证码
     */
    @PostMapping("/sendSmsCode")
    @ApiOperation(value = "验证码验证", tags = "短信发送", notes = "验证码验证")
    public ResponseEntity<SmsDTO> sendSmsCode(@RequestBody JSONObject jsonObject) {
        log.info("验证码验证开始：{}", jsonObject);
        JSONObject obj = memberService.sendSmsCode(jsonObject);
        log.info("验证码验证结束：{}", obj);
        return entityResponse(obj);
    }

    /**
     * 根据会员身份查找会员
     */
    @GetMapping("/getMembershipByIdentity/{value}")
    @ApiOperation(value = "根据会员身份查找会员", tags = "会员信息", notes = "根据会员身份查找会员")
    public ResponseEntity<JSONObject> getMembershipByIdentity(@PathVariable String value) {
        log.info("根据会员身份查找会员开始：{}", value);
        ResponseEntity<JSONObject> obj = memberService.getMembershipByIdentity(value);
        log.info("根据会员身份查找会员结束：{}", obj);
        return obj;
    }
}
